//
//  DouBanViewDetailController.m
//  RACExample
//
//  Created by 山刘 on 2020/6/2.
//  Copyright © 2020 山刘. All rights reserved.
//

#import "DouBanViewDetailController.h"
#import "DouBanDetailTableViewCell.h"
#import "DouBanDetailTableViewCellViewModel.h"
#pragma mark - ====================M层====================
#pragma mark - ====================VM层====================
//定义命令、网络请求、获取数据、发送数据
@interface DouBanDetailViewModel : NSObject
@property (nonatomic, strong) RACSubject *reloadSignal;
@property (nonatomic, copy, readonly) NSArray<DouBanDetailTableViewCellViewModel*> *cellViewModel;
@property (nonatomic, strong, readonly) RACCommand *requestCommand;
@property (nonatomic, strong, readonly) AFHTTPSessionManager *manager;
@end

@interface DouBanDetailViewModel()
@property (nonatomic, copy, readwrite) NSArray<DouBanDetailTableViewCellViewModel*> *cellViewModel;
@end

@implementation DouBanDetailViewModel
#pragma mark - init
-(instancetype)init{
    if (self = [super init]) {
        _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://api.douban.com"]];
        [self racInit];
    }
    return self;
}
#pragma mark - business
- (void)racInit {
    @weakify(self)
    _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        @strongify(self)
        // 网络请求
        RACSignal *requestSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [self.manager GET:@"/v2/movie/in_theaters" parameters:input progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"sendNext");
                [subscriber sendNext:responseObject];
                [subscriber sendCompleted];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [subscriber sendError:error];
                NSLog(@"sendError");
            }];
            return [RACDisposable disposableWithBlock:^{
                NSLog(@"disposableWithBlock");
            }];
        }];
        // 业务逻辑处理
        return [requestSignal map:^id _Nullable(id  _Nullable value) {
            NSLog(@"map");
            NSMutableArray<DouBanDetailTableViewCellViewModel*> *tempt = [NSMutableArray array];
            NSMutableArray *dictArray = value[@"subjects"];
            for (NSDictionary *object in dictArray) {
                DouBanDetailTableViewCellViewModel *cellViewModel = [[DouBanDetailTableViewCellViewModel alloc] init];
                cellViewModel.title = [object valueForKey:@"title"];
                [tempt addObject:cellViewModel];
            }
            self.cellViewModel = [NSArray arrayWithArray:tempt];;
            return nil;
        }];
    }];
}
#pragma mark - getter
@end

#pragma mark - ====================V层====================
@interface DouBanViewDetailController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, strong) DouBanDetailViewModel *viewModel;
@end

@implementation DouBanViewDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self segInitViews];
    [self bindViewModel];
}

#pragma mark - init Views
-(void)segInitViews{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

#pragma mark - RAC Data Binding
- (void)bindViewModel {
    //    @weakify(self)
    //    [[[self.viewModel.requestCommand executionSignals] switchToLatest] subscribeNext:^(id  _Nullable x) {
    //        @strongify(self)
    //        NSLog(@"switchToLatest:%@",x);
    //        [self.tableView reloadData];
    //        [SVProgressHUD dismiss];
    //    }];
    @weakify(self)
    [[self.viewModel.requestCommand executionSignals] subscribeNext:^(RACSignal*  _Nullable x) {
        NSLog(@"subscribeNext1:%@",x);
        [SVProgressHUD show];
        [x subscribeNext:^(id  _Nullable x) {
            NSLog(@"subscribeNext2:%@",x);
            @strongify(self)
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
        }];
    }];
    
    [self.viewModel.requestCommand.errors subscribeNext:^(NSError * _Nullable x) {
        NSLog(@"errors subscribeNext:%@",x);
        [SVProgressHUD dismiss];
    }];
    
    // 发起网络请求
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"apikey"] = @"0df993c66c0c636e29ecbb5344252a4a";
    [self.viewModel.requestCommand execute:parameters];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.viewModel.cellViewModel.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DouBanDetailTableViewCell *cell = [DouBanDetailTableViewCell cellWithTableView:tableView indexPath:indexPath];
    cell.viewModel = self.viewModel.cellViewModel[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*[self.viewModel.cellViewModel[indexPath.row].reloadSignal sendNext:@1];
    [self.viewModel.cellViewModel[indexPath.row].reloadSignal subscribeNext:^(id  _Nullable x) {
    }];
     */
}

#pragma mark - getter
-(DouBanDetailViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[DouBanDetailViewModel alloc]init];
    }
    return _viewModel;
}
@end
